<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="title"
    append-to-body
    width="85%"
    @close="cancel"
  >
    <div class="app-container">
      <el-button size="mini" type="primary" style="float:right;" round @click="doExportExcel">导出</el-button>
      <el-button size="mini" type="primary" style="float:right;" round @click="batchSaveItemInfo">保存</el-button>
      <el-button size="mini" type="primary" style="float:right;" round @click="doReadInfo">获取Item信息</el-button>
      <el-form ref="actionForm" :inline="true" size="small" label-width="100px" label-position="right">
        <el-form-item label="商品号:" label-width="100px">
          <el-input v-model="itemNbr" size="mini" type="textarea" rows="3" placeholder="请输入商品号(多个商品号用空格或换行符隔开)" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="采购ID：" label-width="100px">
          <el-select v-model="buyerId" size="mini" style="width: 280px;">
            <el-option v-for="bid in buyers" :key="bid" :label="bid" :value="bid" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="itemInfo" scope stripe size="mini" border style="width: 100%;" :max-height="tableHeight">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <itemInfo ref="itemInfo" :item-info="scope.row" />
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" width="55" label="序号" />
        <el-table-column :show-overflow-tooltip="true" label="商品号" prop="itemNbr" />
        <el-table-column :show-overflow-tooltip="true" label="部门" prop="deptNbr" />
        <el-table-column :show-overflow-tooltip="true" label="商品说明1" prop="item1Desc" />
        <el-table-column :show-overflow-tooltip="true" label="供应商之商品代码" prop="vendorStockId" />
        <el-table-column :show-overflow-tooltip="true" label="供应商编号" prop="vendorNbr" />
        <el-table-column :show-overflow-tooltip="true" label="供应商名称" prop="vendorName" />
        <el-table-column :show-overflow-tooltip="true" label="商品状态" prop="itemStatusCode" />
        <el-table-column :show-overflow-tooltip="true" label="商品类型" prop="itemTypeCode" />
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click.native.prevent="deleteRow(scope.$index)">移除该项</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { download } from '@/api/download'
import common from '@/api/active-global'
import { queryItemByItemNbr } from '@/api/active-item'
import { batchAddItemInfo } from '@/api/active-item'
import { getBuyerIdList } from '@/api/api'
import itemInfo from '@/views/active-item/create/item-info'
import { showMessage } from '@/utils/activeItemUtil'

export default {
  components: { itemInfo },
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      itemInfo: [],
      loading: false,
      itemNbr: null,
      tableHeight: window.innerHeight * 0.6,
      batchAddItemInfo: this.parent.batchAddItemInfo,
      buyers: [],
      buyerId: null,
      title: ''
    }
  },
  created: function() {
    this.loadBuyer()
  },
  methods: {
    loadBuyer() {
      getBuyerIdList().then((res) => {
        if (res) {
          this.buyers = res
          this.buyerId = res[0]
        }
        // console.log('buyers:' + JSON.stringify(res))
      })
    },
    cancel() {
      this.itemInfo = []
      this.itemNbr = null
      this.showSave = false
      this.showExport = false
    },
    // 读取Item 信息
    doReadInfo() {
      if (this.itemNbr === undefined || this.itemNbr === null || this.itemNbr === '') {
        Message({
          message: '请填写商品号！',
          type: 'warning',
          duration: 3 * 1000
        })
        return
      }
      this.loading = true
      var itemNbr = this.itemNbr.trim() // 去掉两头空格
      itemNbr = itemNbr.replace(/[\n\r\s]/g, ',') // 替换换行符和空字符为','
      var itemNbrs = itemNbr.split(',')
      queryItemByItemNbr(itemNbrs).then(res => {
        if (res && res.length > 0) {
          this.itemInfo = res
          var errorItem = ''
          for (let i = 0; i < itemNbrs.length; i++) {
            console.log(itemNbrs[i] + ' = itemNbrs[i]')
            var errorFalg = false
            res.forEach(_itemNbr => {
              if (_itemNbr.itemNbr.toString() === itemNbrs[i]) {
                console.log(itemNbrs[i] + ' = 存在的')
                errorFalg = true
              }
            })
            if (errorFalg === false) {
              errorItem = errorItem + itemNbrs[i] + ','
            }
          }
          if (errorItem && errorItem.length > 0) {
            Message({
              message: '无效商品号：' + errorItem.substring(0, errorItem.length - 1),
              type: 'warning',
              duration: 3 * 1000
            })
          }
        }
        this.loading = false
      }, (error) => {
        console.log(error)
        this.loading = false
      })
    },
    // 新增一行
    doAddRow() {
      this.data.push({})
    },
    // 删除一行
    deleteRow(index) {
      this.itemInfo.splice(index, 1)
    },
    // 批量导出
    doExportExcel() {
      if (this.itemInfo.length < 1) {
        Message({
          message: '请选择需要导出的item!',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      const itemNbrs = []
      this.itemInfo.forEach(item => {
        itemNbrs.push(item.itemNbr)
      })
      this.$confirm('确认导出选择的 ' + itemNbrs.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var uri = common.basePath + '/exportItemExcel'
        var filename = 'active-item.xlsx'
        if (this.parent.changeType === common.itemType) {
          filename = 'change-type-item.xlsx'
        } else if (this.parent.changeType === common.itemStatus) {
          filename = 'active-item.xlsx'
        }
        console.log('filename:' + filename)
        download(uri, { ids: itemNbrs }, filename)
        this.dialog = false
        this.itemInfo = []
      })
    },
    // 批量保存商品信息
    batchSaveItemInfo() {
      if (this.itemInfo.length < 1) {
        Message({
          message: '请选择需要保存的item!',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      if (this.buyerId === null || this.buyerId === '') {
        Message({
          message: '请选择采购ID',
          type: 'warning',
          duration: 3 * 1000
        })
        return
      }
      const itemNbrs = []
      this.itemInfo.forEach(item => {
        itemNbrs.push(item.itemNbr)
      })
      this.$confirm('确认保存选择的 ' + itemNbrs.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        batchAddItemInfo({ ids: itemNbrs, buyerId: this.buyerId }, this.batchAddItemInfo).then((res) => {
          showMessage(this, res)
          this.parent.toQuery()
          this.loading = false
          this.dialog = false
          this.itemInfo = []
          this.itemNbr = null
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    }
  }
}
</script>

